<template>
  <div class="coding-layout">
    <!-- 顶部导航 -->
    <div class="coding-header">
      <div class="header-content">
        <div class="header-left">
          <el-button text @click="goBack">
            <el-icon><ArrowLeft /></el-icon>
            返回首页
          </el-button>
          <div class="breadcrumb">
            <span>编程实战</span>
            <el-icon><ArrowRight /></el-icon>
            <span>{{ currentTitle || '编程中心' }}</span>
          </div>
        </div>
        
        <div class="header-right">
          <el-button @click="toggleHistory">
            <el-icon><Clock /></el-icon>
            练习记录
          </el-button>
          <el-button @click="toggleSettings">
            <el-icon><Setting /></el-icon>
            编辑器设置
          </el-button>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="coding-main">
      <router-view />
    </div>

    <!-- 练习记录抽屉 -->
    <el-drawer
      v-model="showHistory"
      title="练习记录"
      direction="rtl"
      size="400px"
    >
      <div class="history-content">
        <div class="history-stats">
          <div class="stat-item">
            <div class="stat-number">{{ codingStats.totalProblems }}</div>
            <div class="stat-label">解决题目</div>
          </div>
          <div class="stat-item">
            <div class="stat-number">{{ codingStats.totalSubmissions }}</div>
            <div class="stat-label">提交次数</div>
          </div>
          <div class="stat-item">
            <div class="stat-number">{{ codingStats.acceptanceRate }}%</div>
            <div class="stat-label">通过率</div>
          </div>
        </div>
        
        <div class="history-list">
          <div 
            v-for="record in codingHistory" 
            :key="record.id"
            class="history-item"
          >
            <div class="problem-info">
              <div class="problem-title">{{ record.problemTitle }}</div>
              <div class="problem-meta">
                <span class="problem-date">{{ formatDate(record.submittedAt) }}</span>
                <span class="problem-language">{{ record.language }}</span>
              </div>
            </div>
            <div class="problem-result">
              <div class="status" :class="getStatusClass(record.status)">
                {{ getStatusText(record.status) }}
              </div>
              <div class="runtime" v-if="record.runtime">
                {{ record.runtime }}ms
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-drawer>

    <!-- 编辑器设置抽屉 -->
    <el-drawer
      v-model="showSettings"
      title="编辑器设置"
      direction="rtl"
      size="350px"
    >
      <div class="settings-content">
        <div class="setting-group">
          <label>编程语言</label>
          <el-select v-model="editorSettings.language" @change="handleLanguageChange">
            <el-option label="JavaScript" value="javascript" />
            <el-option label="Python" value="python" />
            <el-option label="Java" value="java" />
            <el-option label="C++" value="cpp" />
            <el-option label="Go" value="go" />
          </el-select>
          <div class="setting-desc">选择您偏好的编程语言</div>
        </div>
        
        <div class="setting-group">
          <label>主题</label>
          <el-select v-model="editorSettings.theme" @change="handleThemeChange">
            <el-option label="VS Code Dark" value="vs-dark" />
            <el-option label="VS Code Light" value="vs-light" />
            <el-option label="Monokai" value="monokai" />
            <el-option label="GitHub" value="github" />
          </el-select>
          <div class="setting-desc">选择编辑器主题</div>
        </div>
        
        <div class="setting-group">
          <label>字体大小</label>
          <el-slider 
            v-model="editorSettings.fontSize" 
            :min="12" 
            :max="24" 
            :step="2"
            @change="handleFontSizeChange"
          />
          <div class="setting-desc">当前大小：{{ editorSettings.fontSize }}px</div>
        </div>
        
        <div class="setting-group">
          <label>自动补全</label>
          <el-switch v-model="editorSettings.autoComplete" @change="handleAutoCompleteChange" />
          <div class="setting-desc">启用代码自动补全功能</div>
        </div>
        
        <div class="setting-group">
          <label>代码格式化</label>
          <el-switch v-model="editorSettings.autoFormat" @change="handleAutoFormatChange" />
          <div class="setting-desc">保存时自动格式化代码</div>
        </div>
        
        <div class="setting-group">
          <label>显示行号</label>
          <el-switch v-model="editorSettings.lineNumbers" @change="handleLineNumbersChange" />
          <div class="setting-desc">在编辑器中显示行号</div>
        </div>
        
        <div class="setting-group">
          <label>代码折叠</label>
          <el-switch v-model="editorSettings.codeFolding" @change="handleCodeFoldingChange" />
          <div class="setting-desc">启用代码块折叠功能</div>
        </div>
        
        <div class="setting-actions">
          <el-button @click="resetSettings">重置设置</el-button>
          <el-button type="primary" @click="saveSettings">保存设置</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { 
  ArrowLeft, ArrowRight, Clock, Setting
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const router = useRouter()
const route = useRoute()

// 响应式数据
const showHistory = ref(false)
const showSettings = ref(false)

// 计算当前页面标题
const currentTitle = computed(() => {
  return route.meta?.title || ''
})

// 编程统计数据
const codingStats = ref({
  totalProblems: 45,
  totalSubmissions: 128,
  acceptanceRate: 78
})

// 编程记录
const codingHistory = ref([
  {
    id: 1,
    problemTitle: '两数之和',
    status: 'accepted',
    runtime: 68,
    language: 'JavaScript',
    submittedAt: new Date('2024-01-15')
  },
  {
    id: 2,
    problemTitle: '反转链表',
    status: 'accepted',
    runtime: 52,
    language: 'Python',
    submittedAt: new Date('2024-01-14')
  },
  {
    id: 3,
    problemTitle: '最长回文子串',
    status: 'wrong_answer',
    runtime: null,
    language: 'Java',
    submittedAt: new Date('2024-01-13')
  },
  {
    id: 4,
    problemTitle: '合并两个有序数组',
    status: 'time_limit_exceeded',
    runtime: null,
    language: 'C++',
    submittedAt: new Date('2024-01-12')
  }
])

// 编辑器设置
const editorSettings = ref({
  language: 'javascript',
  theme: 'vs-dark',
  fontSize: 14,
  autoComplete: true,
  autoFormat: true,
  lineNumbers: true,
  codeFolding: true
})

// 方法
const goBack = () => {
  router.push('/')
}

const toggleHistory = () => {
  showHistory.value = !showHistory.value
}

const toggleSettings = () => {
  showSettings.value = !showSettings.value
}

const formatDate = (date) => {
  return new Date(date).toLocaleDateString('zh-CN', {
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const getStatusClass = (status) => {
  const classes = {
    'accepted': 'success',
    'wrong_answer': 'error',
    'time_limit_exceeded': 'warning',
    'runtime_error': 'error',
    'compile_error': 'error'
  }
  return classes[status] || 'default'
}

const getStatusText = (status) => {
  const texts = {
    'accepted': '通过',
    'wrong_answer': '答案错误',
    'time_limit_exceeded': '超时',
    'runtime_error': '运行错误',
    'compile_error': '编译错误'
  }
  return texts[status] || '未知'
}

const handleLanguageChange = (language) => {
  ElMessage.success(`已切换到 ${language}`)
  // 触发全局事件，通知编辑器更新语言
  window.dispatchEvent(new CustomEvent('editor-language-change', { detail: language }))
}

const handleThemeChange = (theme) => {
  ElMessage.success('主题已更新')
  // 触发全局事件，通知编辑器更新主题
  window.dispatchEvent(new CustomEvent('editor-theme-change', { detail: theme }))
}

const handleFontSizeChange = (fontSize) => {
  // 触发全局事件，通知编辑器更新字体大小
  window.dispatchEvent(new CustomEvent('editor-fontsize-change', { detail: fontSize }))
}

const handleAutoCompleteChange = (enabled) => {
  ElMessage.success(`自动补全已${enabled ? '启用' : '禁用'}`)
  window.dispatchEvent(new CustomEvent('editor-autocomplete-change', { detail: enabled }))
}

const handleAutoFormatChange = (enabled) => {
  ElMessage.success(`自动格式化已${enabled ? '启用' : '禁用'}`)
  window.dispatchEvent(new CustomEvent('editor-autoformat-change', { detail: enabled }))
}

const handleLineNumbersChange = (enabled) => {
  window.dispatchEvent(new CustomEvent('editor-linenumbers-change', { detail: enabled }))
}

const handleCodeFoldingChange = (enabled) => {
  window.dispatchEvent(new CustomEvent('editor-codefolding-change', { detail: enabled }))
}

const resetSettings = () => {
  editorSettings.value = {
    language: 'javascript',
    theme: 'vs-dark',
    fontSize: 14,
    autoComplete: true,
    autoFormat: true,
    lineNumbers: true,
    codeFolding: true
  }
  ElMessage.success('设置已重置')
}

const saveSettings = () => {
  // 保存设置到本地存储
  localStorage.setItem('coding-editor-settings', JSON.stringify(editorSettings.value))
  ElMessage.success('设置已保存')
}

// 生命周期
onMounted(() => {
  // 从本地存储加载设置
  const savedSettings = localStorage.getItem('coding-editor-settings')
  if (savedSettings) {
    try {
      editorSettings.value = { ...editorSettings.value, ...JSON.parse(savedSettings) }
    } catch (error) {
      console.warn('Failed to load editor settings:', error)
    }
  }
})
</script>

<style lang="scss" scoped>
.coding-layout {
  min-height: 100vh;
  background: var(--el-bg-color-page);
  display: flex;
  flex-direction: column;
}

.coding-header {
  background: white;
  border-bottom: 1px solid var(--el-border-color-extra-light);
  padding: 16px 0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
  
  .breadcrumb {
    display: flex;
    align-items: center;
    gap: 8px;
    color: var(--el-text-color-secondary);
    font-size: 14px;
  }
}

.header-right {
  display: flex;
  gap: 12px;
}

.coding-main {
  flex: 1;
  overflow: hidden;
}

.history-content {
  .history-stats {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 16px;
    margin-bottom: 24px;
    
    .stat-item {
      text-align: center;
      padding: 16px;
      background: var(--el-fill-color-extra-light);
      border-radius: 8px;
      
      .stat-number {
        font-size: 24px;
        font-weight: 700;
        color: var(--el-color-primary);
        margin-bottom: 4px;
      }
      
      .stat-label {
        font-size: 12px;
        color: var(--el-text-color-secondary);
      }
    }
  }
  
  .history-list {
    .history-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 16px;
      border: 1px solid var(--el-border-color-lighter);
      border-radius: 8px;
      margin-bottom: 12px;
      
      .problem-info {
        flex: 1;
        
        .problem-title {
          font-weight: 500;
          margin-bottom: 4px;
          color: var(--el-text-color-primary);
        }
        
        .problem-meta {
          display: flex;
          gap: 12px;
          font-size: 12px;
          color: var(--el-text-color-placeholder);
        }
      }
      
      .problem-result {
        text-align: right;
        
        .status {
          font-size: 12px;
          font-weight: 500;
          margin-bottom: 2px;
          
          &.success {
            color: var(--el-color-success);
          }
          
          &.error {
            color: var(--el-color-danger);
          }
          
          &.warning {
            color: var(--el-color-warning);
          }
        }
        
        .runtime {
          font-size: 11px;
          color: var(--el-text-color-placeholder);
        }
      }
    }
  }
}

.settings-content {
  .setting-group {
    margin-bottom: 24px;
    
    label {
      display: block;
      margin-bottom: 8px;
      font-weight: 500;
      color: var(--el-text-color-primary);
    }
    
    .setting-desc {
      margin-top: 4px;
      font-size: 12px;
      color: var(--el-text-color-placeholder);
    }
    
    .el-select {
      width: 100%;
    }
  }
  
  .setting-actions {
    display: flex;
    gap: 12px;
    padding-top: 20px;
    border-top: 1px solid var(--el-border-color-extra-light);
    
    .el-button {
      flex: 1;
    }
  }
}

@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    gap: 12px;
  }
  
  .header-left,
  .header-right {
    width: 100%;
    justify-content: center;
  }
  
  .history-stats {
    grid-template-columns: 1fr;
  }
  
  .history-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
    
    .problem-result {
      text-align: left;
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
}
</style>
